//The MIT License
//
//Copyright (c) 2009 nodchip
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
package tv.dyndns.kishibe.server;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import tv.dyndns.kishibe.client.Constant;
import tv.dyndns.kishibe.client.Service;
import tv.dyndns.kishibe.client.game.GameMode;
import tv.dyndns.kishibe.client.packet.PacketBbsResponse;
import tv.dyndns.kishibe.client.packet.PacketBbsThread;
import tv.dyndns.kishibe.client.packet.PacketChatData;
import tv.dyndns.kishibe.client.packet.PacketGameStatus;
import tv.dyndns.kishibe.client.packet.PacketLinkData;
import tv.dyndns.kishibe.client.packet.PacketMatchingPlayer;
import tv.dyndns.kishibe.client.packet.PacketProblemCreationLog;
import tv.dyndns.kishibe.client.packet.PacketProblemData;
import tv.dyndns.kishibe.client.packet.PacketProblemDataReport;
import tv.dyndns.kishibe.client.packet.PacketRankingData;
import tv.dyndns.kishibe.client.packet.PacketRatingDistribution;
import tv.dyndns.kishibe.client.packet.PacketRegistrationData;
import tv.dyndns.kishibe.client.packet.PacketResult;
import tv.dyndns.kishibe.client.packet.PacketRoomKey;
import tv.dyndns.kishibe.client.packet.PacketServerStatus;
import tv.dyndns.kishibe.client.packet.PacketUserData;
import tv.dyndns.kishibe.client.packet.PacketWrongAnswer;
import tv.dyndns.kishibe.server.handwriting.Factory;
import tv.dyndns.kishibe.server.handwriting.Recognizer;
import tv.dyndns.kishibe.server.relevance.RelevantProblem;
import tv.dyndns.kishibe.server.util.ParallelComputation;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class ServiceImpl extends RemoteServiceServlet implements Service {
	private static final long serialVersionUID = 5332557696674555396L;
	private final Random random = new Random();
	private final transient ChatManager chatManager = new ChatManager();
	private final transient GameManager gameManager = new GameManager();
	private final transient BadUserManager badUserManager = new BadUserManager();
	private final transient PlayerHistoryManager playerHistoryManager = new PlayerHistoryManager();
	private final transient VoteManager voteManager = new VoteManager();
	private final transient Recognizer recognizer = Factory.createInstance();
	private final transient ThemeModeEditorManager themeModeEditorManager = new ThemeModeEditorManager();

	public ServiceImpl() {
		ProblemManager.getInstance();
		PrefectureRanking.getInstance();
		RatingDistribution.getInstance();
	}

	@Override
	public void destroy() {
		ThreadPool.getInstance().getService().shutdown();
		ParallelComputation.exit();
		super.destroy();
	}

	// 最後に遊んだ人たちを取得する
	public String[] getPlayerHistory() {
		return playerHistoryManager.get();
	}

	// サーバーの状態を取得する
	public PacketServerStatus getServerStatus(boolean isFirst, int userCode) {
		final PacketServerStatus serverStatus = gameManager.getServerStatus(isFirst, userCode);
		serverStatus.lastestPlayers = playerHistoryManager.get();
		return serverStatus;
	}

	// プレイヤー情報を登録する
	private Object lockObjectRegister = new Object();

	@Override
	public PacketRegistrationData register(String name, int genre, int type, String greeting, GameMode gameMode, String roomName, String theme, String imageFileName, int classLevel, int difficultSelect, int rating, int userCode, boolean newProblem, boolean publicEvent) {
		playerHistoryManager.push(name);

		final PlayerStatus status;
		synchronized (lockObjectRegister) {
			final Game session = gameManager.getMatchingSession(gameMode, roomName, classLevel, theme, genre, type, publicEvent);
			status = session.addPlayer(name, genre, type, greeting, imageFileName, classLevel, difficultSelect, rating, userCode, newProblem);
		}

		final PacketRegistrationData data = new PacketRegistrationData();
		data.playerId = status.getPlayerId();
		data.playerListIndex = status.getPlayerListId();
		data.sessionId = status.getSessionId();

		return data;
	}

	// マッチング
	// 他の対戦者の参加を待つ
	public int waitForMatching(int sessionId, int playerId) {
		final Game session = gameManager.getSession(sessionId);

		if (session == null) {
			return -1;
		}

		int transition = session.getTransition();
		if (transition != Constant.TRANSITION_MATCHING) {
			return 0;
		}

		return session.getRestMatchingSecond();
	}

	// マッチング中の相手のデータを取得する
	public PacketMatchingPlayer[] getMachingPlayer(int sessionId) {
		final Game session = gameManager.getSession(sessionId);

		if (session == null) {
			return null;
		}

		return session.getMatchingPlayer();
	}

	// 強制的にゲームをスタートさせる
	public int requestSkip(int sessionId, int playerListId) {
		final Game session = gameManager.getSession(sessionId);

		if (session == null) {
			return Integer.MAX_VALUE;
		}

		session.requestStartingGame(playerListId);
		return session.getNumberOfPlayer();
	}

	// ゲーム開始待機
	// ゲームの開始を待つ
	public int waitForGame(int sessionId) {
		final Game session = gameManager.getSession(sessionId);

		if (session == null) {
			return Integer.MAX_VALUE;
		}

		if (session.getTransition() != Constant.TRANSITION_READY_FOR_GAME) {
			return 0;
		}

		return session.getRestWaitForGameSecond();
	}

	// 問題を取得する
	public PacketProblemData[] getProblemData(int sessionId) {
		final Game session = gameManager.getSession(sessionId);

		if (session == null || session.getTransition() == Constant.TRANSITION_MATCHING) {
			return null;
		}

		return session.getProblemData();
	}

	// 他のプレイヤーの名前を取得する
	public String[] getPlayerNameList(int sessionId) {
		final Game session = gameManager.getSession(sessionId);

		if (session == null) {
			return null;
		}

		return session.getPlayerNameList();
	}

	// ゲーム
	// 自分の解答を送る
	public Boolean sendAnswer(int sessionId, int playerListId, String answer) {
		final Game session = gameManager.getSession(sessionId);

		if (session == null) {
			return false;
		}

		session.receiveAnswer(playerListId, answer);

		return true;
	}

	// ゲームの進行状態を取得する
	public PacketGameStatus getGameStatus(int sessionId, int playerListId) {
		final Game session = gameManager.getSession(sessionId);

		if (session == null) {
			return null;
		}

		session.keepAlive(playerListId);

		return session.getGameStatus(playerListId);
	}

	// 結果表示
	// 最終結果を取得する
	public PacketResult[] getResult(int sessionId) {
		final Game session = gameManager.getSession(sessionId);

		if (session == null) {
			return null;
		}

		return session.getPacketResult();
	}

	// チャットにメッセージを送信する
	public void sendMessageToChat(PacketChatData chatData) {
		// ロックはChatManager側で行う
		chatManager.write(chatData, getRemoveAddr());
	}

	// チャットからメッセージを受信する
	public PacketChatData[] receiveMessageFromChat(int lastestResId) {
		// ロックはChatManager側で行う
		return chatManager.read(lastestResId);
	}

	// 問題を投稿する
	private final Object fileLock = new Object();

	public int uploadProblem(final PacketProblemData problemData, final int userCode) {
		final String ip = getRemoveAddr();

		ThreadPool.getInstance().execute(new Runnable() {
			public void run() {
				synchronized (fileLock) {
					try {
						final FileOutputStream fos = new FileOutputStream("/var/www/html/qmaclone/problem.log", true);
						final OutputStreamWriter osw = new OutputStreamWriter(fos, "MS932");
						final BufferedWriter bw = new BufferedWriter(osw);
						String msg = problemData.toString() + "\r\n" + userCode + "\t" + ip + "\t" + Calendar.getInstance().getTime() + "\r\n";
						bw.write(msg);

						bw.close();
						osw.close();
						fos.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		});

		final ProblemManager manager = ProblemManager.getInstance();

		if (badUserManager.isLimitedUserToCreation(userCode, ip)) {
			if (problemData.problemId == -1) {
				return manager.getNumberOfProblem() + 1;
			} else {
				return problemData.problemId;
			}
		}

		final int problemID;

		if (problemData.problemId == -1) {
			problemID = manager.addProblemData(problemData);
		} else {
			manager.updateProblemData(problemData);
			problemID = problemData.problemId;
		}

		ThreadPool.getInstance().execute(new Runnable() {
			public void run() {
				DatabaseFactory.getInstance().addCreationLog(problemID, userCode, ip);
			}
		});

		return problemID;
	}

	// 問題を取得する
	public PacketProblemData[] getProblemList(List<Integer> problemIds) {
		return DatabaseFactory.getInstance().getProblemData(problemIds);
	}

	// 問題統計情報を取得する
	public PacketProblemDataReport getProblemDataReport() {
		PacketProblemDataReport report = new PacketProblemDataReport();
		report.count = ProblemManager.getInstance().getTableProblemCount();
		report.rate = ProblemManager.getInstance().getTableProblemRatio();
		return report;
	}

	public int[][] getStatisticsOfProblemCount() {
		return ProblemManager.getInstance().getTableProblemCount();
	}

	public int[][] getStatisticsOfAccuracyRate() {
		return ProblemManager.getInstance().getTableProblemRatio();
	}

	// 問題を検索する
	@Override
	public PacketProblemData[] searchProblem(String query, String creater, int genre, int type, int randomFlag) {
		return DatabaseFactory.getInstance().searchProblem(query, creater, genre, type, randomFlag);
	}

	private final RelevantProblem relevantProblem = new RelevantProblem();

	public PacketProblemData[] searchSimilarProblem(String query) {
		try {
			final List<Integer> problemIds = relevantProblem.search(query);
			if (!problemIds.isEmpty()) {
				return DatabaseFactory.getInstance().getProblemData(problemIds);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return DatabaseFactory.getInstance().searchSimilarProblemData(query);
	}

	public int getSessionTransition(int sessionId) {
		return gameManager.getSession(sessionId).getTransition();
	}

	public int getNewUserCode() {
		int userCode = random.nextInt(100000000);
		if (userCode < 0) {
			userCode *= -1;
		}
		return userCode;
	}

	public void addProblemIdsToReport(final int userCode, final int[] problemIds) {
		DatabaseFactory.getInstance().addProblemIdsToReport(userCode, problemIds);
	}

	public void removeProblemIDFromReport(int userCode, int problemID) {
		DatabaseFactory.getInstance().removeProblemIdFromReport(userCode, problemID);
	}

	public void clearProblemIDFromReport(int userCode) {
		DatabaseFactory.getInstance().clearProblemIdFromReport(userCode);
	}

	public PacketProblemData[] getUserProblemReport(int userCode) {
		return DatabaseFactory.getInstance().getUserProblemReport(userCode);
	}

	public PacketUserData loadUserData(int userCode) {
		return DatabaseFactory.getInstance().getUserData(userCode);
	}

	public void saveUserData(PacketUserData userData) {
		DatabaseFactory.getInstance().setUserData(userData);
	}

	public PacketUserData[] getLoginUsers() {
		return gameManager.getLoginUsers();
	}

	public void reportLogin(int userCode) {
		gameManager.reportLogin(userCode);
	}

	public PacketWrongAnswer[] getWrongAnswers(int problemID) {
		return DatabaseFactory.getInstance().getPlayerAnswers(problemID);
	}

	public void removePlayerAnswers(final int problemID) {
		ThreadPool.getInstance().execute(new Runnable() {
			public void run() {
				DatabaseFactory.getInstance().removePlayerAnswers(problemID);
			}
		});
	}

	public PacketRankingData[][] getRankingData() {
		return DatabaseFactory.getInstance().getRankingData();
	}

	public void addIgnoreUserCode(int userCode, int targetUserCode) {
		badUserManager.addIgnoreUserCode(userCode, targetUserCode);
	}

	public void removeIgnoreUserCode(int userCode, int targetUserCode) {
		badUserManager.removeIgnoreUserCode(userCode, targetUserCode);
	}

	public String getRemoveAddr() {
		return getThreadLocalRequest().getRemoteAddr();
	}

	public boolean isLimitedUser(int userCode) {
		final String ip = getRemoveAddr();
		return badUserManager.isLimitedUserToCreation(userCode, ip);
	}

	public PacketProblemCreationLog[] getProblemCreationLog(int problemId) {
		return DatabaseFactory.getInstance().getProblemCreationHistory(problemId);
	}

	public PacketBbsResponse[] getBbsResponses(int threadId, int count) {
		return DatabaseFactory.getInstance().getBbsResponses(threadId, count);
	}

	public PacketBbsThread[] getBbsThread(int start, int count) {
		return DatabaseFactory.getInstance().getBbsThread(start, count);
	}

	public void buildBbsThread(PacketBbsThread thread, PacketBbsResponse response) {
		response.machineIp = getRemoveAddr();

		if (badUserManager.isLimitedUserToCreation(response.userCode, response.machineIp)) {
			return;
		}
		DatabaseFactory.getInstance().buildBbsThread(thread, response);
	}

	public void writeToBbs(PacketBbsResponse response, boolean age) {
		response.machineIp = getRemoveAddr();

		if (badUserManager.isLimitedUserToCreation(response.userCode, response.machineIp)) {
			return;
		}

		DatabaseFactory.getInstance().writeToBbs(response, age);
	}

	public int getNumberOfBbsThreads() {
		return DatabaseFactory.getInstance().getNumberOfBbsThread();
	}

	public void addLinkData(PacketLinkData linkData) {
		DatabaseFactory.getInstance().addLinkData(linkData);
	}

	public PacketLinkData[] getLinkDatas(int start, int count) {
		return DatabaseFactory.getInstance().getLinkDatas(start, count);
	}

	public int getNumberOfLinkDatas() {
		return DatabaseFactory.getInstance().getNumberOfLinkDatas();
	}

	public void removeLinkData(int id) {
		DatabaseFactory.getInstance().removeLinkData(id);
	}

	public void updateLinkData(PacketLinkData linkData) {
		DatabaseFactory.getInstance().updateLinkData(linkData);
	}

	public int[][] getPrefectureRanking() {
		return PrefectureRanking.getInstance().get();
	}

	public void addRatingHistory(int userCode, int rating) {
		DatabaseFactory.getInstance().addRatingHistory(userCode, rating);
	}

	public int[] getRatingHistory(int userCode) {
		return DatabaseFactory.getInstance().getRatingHistory(userCode);
	}

	public PacketRatingDistribution getRatingDistribution() {
		return RatingDistribution.getInstance().get();
	}

	public String[] getThemeModeThemes() {
		return ProblemManager.getInstance().getThemeModeThemes();
	}

	public Map<String, PacketRankingData[]> getThemeModeRanking() {
		return DatabaseFactory.getInstance().getThemeModeRankingData();
	}

	@Override
	public List<PacketRoomKey> getEventRooms() {
		return gameManager.getEventRooms();
	}

	@Override
	public void voteToProblem(int userCode, int problemId, boolean good, String feedback) {
		voteManager.vote(userCode, problemId, good, feedback);
	}

	@Override
	public String[] recognizeHandwriting(double[][][] strokes) {
		return recognizer.recognize(strokes);
	}

	@Override
	public Set<String> getAvailableChalactersForHandwriting() {
		return recognizer.getAvailableCharacters();
	}

	@Override
	public void clearProblemFeedback(int problemId) {
		DatabaseFactory.getInstance().clearProblemFeedback(problemId);
	}

	@Override
	public List<String> getProblemFeedback(int problemId) {
		return DatabaseFactory.getInstance().getProblemFeedback(problemId);
	}

	@Override
	public Map<String, List<String>> getThemeModeQuery() {
		return DatabaseFactory.getInstance().getThemeModeQuery();
	}

	@Override
	public void addThemeModeQuery(String theme, String query) {
		DatabaseFactory.getInstance().addThemeModeQuery(theme, query);
	}

	@Override
	public void removeThemeModeQuery(String theme, String query) {
		DatabaseFactory.getInstance().removeThemeModeQuery(theme, query);
	}

	@Override
	public boolean isThemeModeEditor(int userCode) {
		return themeModeEditorManager.isThemeModeEditor(userCode);
	}

	@Override
	public void applyThemeModeEditor(int userCode, String text) {
		themeModeEditorManager.applyThemeModeEditor(userCode, text);
	}

	@Override
	public void acceptThemeModeEditor(int userCode) {
		themeModeEditorManager.acceptThemeModeEditor(userCode);
	}

	@Override
	public void rejectThemeModeEditor(int userCode) {
		themeModeEditorManager.rejectThemeModeEditor(userCode);
	}

	@Override
	public Map<Integer, Integer> getThemeModeEditors() {
		return themeModeEditorManager.getThemeModeEditors();
	}

	@Override
	public boolean isApplyingThemeModeEditor(int userCode) {
		return themeModeEditorManager.isApplyingThemeModeEditor(userCode);
	}
}
